#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "framework/FWCommon.h"

#import "PIObject.h"


static NSInteger const kNotesMaxLength = 256;


@implementation PIObject

@synthesize native, title, icon, startDate, startDateRaw, calendar, calendarIcon, calendarColor, repeating, notes, tags, alarms, sensitivity, augmented, recurrance;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)init
{
    if ((self = [super init])) {
        sensitivity = PISensitivityTypeNone;
    }
    
    return self;
}

- (void)dealloc
{
    [title release];
    [icon release];

    [startDate release];
    
    [calendar release];
    [calendarColor release];
    [calendarIcon release];
    
    [tags release];
    
    [notes release];
    [alarms release];
    [recurrance release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Information access

- (NSString*)notesSummary
{
    if (!notes)
        return nil;
    
    NSString* trim = [notes stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    // If notes lenth is below the max length then we are OK
    if (trim.length <= kNotesMaxLength)
        return trim;

    NSCharacterSet* newLines = [NSCharacterSet controlCharacterSet];
    for (NSUInteger pos = kNotesMaxLength; pos < trim.length; ++pos) {
        if ([newLines characterIsMember:[trim characterAtIndex:pos]])
            return [trim substringToIndex:pos];
    }

    return [trim substringToIndex:kNotesMaxLength];
}

@end


// ******************************************************************************************
#pragma mark -
#pragma mark Object access from arrays

@implementation NSArray (PIObject)

- (id)piObjectForKey:(NSString*)key
{
    return [self fwDisplayObjectForKey:key];
}

@end